import { createStore, applyMiddleware, compose } from 'redux'
import flatten from 'flatten'
import window from 'global/window'
import { returnSelf, isArray } from './utils'

export default function ({
    reducers,
    initialState,
    plugin,
    sagaMiddleware,
    promiseMiddlware,
    createOpts: { setupMiddleware = returnSelf }
}) {
    const extraEnhancers = plugin.get('extraEnhancers')
    invariant(
        isArray(extraEnhancers),
        `[app.start] extraEnhancers should be array, but got ${typeof extraEnhancers}`
    )

    const extraMiddlewares = plugin.get('onAction')
    const middlewares = setupMiddleware([
        promiseMiddlware,
        sagaMiddleware,
        ...flatten(extraMiddlewares)
    ])

    let devtools = () => noop => noop
    
    if (
        process.env.NODE_ENV !== 'production' &&
        window.__REDUX__DEVTOOLS_EXTENSION__
    ) {
        devtools = window.__REDUX__DEVTOOLS_EXTENSION__
    }

    const enhancers = [
        applyMiddleware(...middlewares),
        ...extraEnhancers,
        devtools(window.__REDUX__DEVTOOLS_EXTENSION__)
    ]

    return createStore(reducers, initialState, compose(...enhancers))
}